package com.lzl.logdesenshelper.utils;

import com.alibaba.fastjson.serializer.ValueFilter;
import com.lzl.logdesenshelper.annotation.LogField;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;

public class SensitiveValueFilter implements ValueFilter {
    @Override
    public Object process(Object obj, String key, Object value) {
        if (null == obj) {
            return value;
        }
        // 是否是接口
        if (obj.getClass().isInterface()) {
            return value;
        }
        if (TypeUtil.isPrimitive(obj.getClass())) {
            if (!(obj instanceof String)) {
                return value;
            }
            LogField annotation = obj.getClass().getAnnotation(LogField.class);
            if (annotation == null) {
                return value;
            }
            String param = obj.toString();
            return DesensitizationUtil.desensitizeValue(annotation, param);
        }
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        while (null != clazz.getSuperclass() && !Object.class.equals(clazz.getSuperclass())) {
            fields = (Field[]) ArrayUtils.addAll(fields, clazz.getSuperclass().getDeclaredFields());
            clazz = clazz.getSuperclass();
        }
        for (Field field : fields) {
            if (field.getName().equals(key)) {
                LogField annotation = field.getDeclaredAnnotation(LogField.class);
                if (field.getType().equals(String.class) && null != annotation) {
                    if (StringUtils.isNotBlank((String) value)) {
                        return DesensitizationUtil.desensitizeValue(annotation, (String) value);
                    }
                }
            }
        }
        return value;
    }

}
